﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc.Mailer;
using RoccaStore.Mailers;
using RoccaStore.Services;
using RoccaStore.Utils;
using RoccaStore.Web.Filters;
using RoccaStore.Web.Models;

namespace RoccaStore.Web.Controllers
{
    [AccountFilter]
    public class HomeController : Controller
    {
        private readonly IFileSendService _fileSendService;
        private readonly IFileInfoService _fileInfoService;
        private readonly IUserMailer _userMailer;
        private readonly ISlugService _slugService;

        public HomeController(
            IFileSendService fileSendService,
            IFileInfoService fileInfoService,
            IUserMailer userMailer,
            ISlugService slugService)
        {
            _fileSendService = fileSendService;
            _fileInfoService = fileInfoService;
            _userMailer = userMailer;
            _slugService = slugService;
        }

        public ActionResult Index(string slug, string hash)
        {
            if (string.IsNullOrEmpty(slug) || slug.Contains("page"))
            {
                return View();
            }
            else
            {
                Slug fileSlug = _slugService.GetByName(slug);

                if (fileSlug.Deleted.HasValue)
                    return RedirectToAction("Deleted", "Errors");

                List<Slug> group = _slugService.GetByParent(fileSlug.Name);

                if (fileSlug != null)
                {
                    var model = new FileViewModel()
                    {
                        File = fileSlug.File,
                        Group = group,
                        HashedData = hash,
                        Slug = fileSlug
                    };

                    bool isValidHash = (!string.IsNullOrEmpty(hash) && hash.Equals(fileSlug.Key));

                    if (!string.IsNullOrEmpty(hash) && !hash.Equals(fileSlug.Key))
                    {
                        try
                        {
                            // attempt decode incoming data
                            dynamic details = HashUtils.DecodeDynamicHash(hash, fileSlug.Key);
                            isValidHash = true;
                        }
                        catch (Exception)
                        {
                            return RedirectToAction("NotFound", "Errors");
                        }
                    }

                    if (fileSlug.IsSecure && !isValidHash)
                        return RedirectToAction("SecuredFile", "Errors");

                    return View("File", model);
                }
                else
                    return RedirectToAction("NotFound", "Errors");
            }
        }
    }
}
